package com.mobilepay.moneypig.model.dialog;

import android.content.Context;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.mobilepay.moneypig.R;
import com.mobilepay.moneypig.base.BaseDialog;
import com.mobilepay.moneypig.config.NetConfig;
import com.mobilepay.moneypig.model.application.App;
import com.mobilepay.moneypig.okhttp.HttpUtils;
import com.mobilepay.moneypig.response.ResponseResult;
import com.mobilepay.moneypig.response.home.CreditListData;
import com.mobilepay.moneypig.utils.CommonUtil;
import com.mobilepay.moneypig.utils.GsonUtil;
import com.mobilepay.moneypig.utils.acache.ACache;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by xlm on 2017/8/2 0002
 */

public class CreditDialog extends BaseDialog {
    public CreditDialog(Context context) {
        super(context);
    }

    public CreditDialog(Context context, int themeResId) {
        super(context, themeResId);
    }

    protected CreditDialog(Context context, boolean cancelable, OnCancelListener cancelListener) {
        super(context, cancelable, cancelListener);
    }

    private RecyclerView mRecycleCredit;
    private List<CreditListData.DataBean> dataBeanList;
    private CreditAdapter creditAdapter;
    private TextView mTextCancle;

    @Override
    protected void onSetContentView() {
        setContentView(R.layout.dialog_choose_credit);
    }

    @Override
    protected void initViews() {
        mRecycleCredit = (RecyclerView) findViewById(R.id.choose_recycle);
        mTextCancle = (TextView) findViewById(R.id.credit_cancle);
        initWindow(1.0f, 0.45f, Gravity.BOTTOM);
        setAnimate(R.style.animatedialog);
    }

    @Override
    protected void onSetListener() {
        mTextCancle.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                cancel();
            }
        });
    }

    @Override
    protected void afterOnCreate(Bundle savedInstanceState) {
        setCreditAdapter();
    }

    public void upDateCreditList() {
        getCreditList();
    }

    private void getCreditList() {
        HttpUtils.RequestParam param = new HttpUtils.RequestParam();
        param.add("method", NetConfig.creditCard);
        param.add("uid", String.valueOf(App.getApp().getUserInfo().getData().getUid()));
        param.add("sign", param.getMd5String());
        HttpUtils.getInstance().params(param).executePost(new HttpUtils.HttpListener() {
            @Override
            public void onException(Throwable e) {
                super.onException(e);
                if (CommonUtil.isForeground(getActivity())) {
                    showToastShort(getActivity().getString(R.string.net_state));
                    String jsonString = ACache.get(App.getApp()).getAsString(NetConfig.creditCard);
                    if (!CommonUtil.isEmpty(jsonString)) {
                        setCreditData(jsonString);
                    }
                }
            }

            @Override
            public void onHttpSuccess(String string) {
                super.onHttpSuccess(string);
                if (HttpUtils.isJson(string)) {
                    ResponseResult responseResult = GsonUtil.GsonToBean(string, ResponseResult.class);
                    if (responseResult.getStatus() == 1) {
                        setCreditData(string);
                        ACache.get(App.getApp()).put(NetConfig.creditCard, string);
                    } else {
                        showToastShort(responseResult.getInfo());
                    }
                }
            }
        });
    }

    private void setCreditData(String string) {
        CreditListData data = GsonUtil.GsonToBean(string, CreditListData.class);
        if (data.getData().size() != 0) {
            dataBeanList.clear();
            dataBeanList.addAll(data.getData());
        }
        creditAdapter.setData(dataBeanList);
        getActivity().runOnUiThread(new Runnable() {
            @Override
            public void run() {
                creditAdapter.notifyDataSetChanged();
            }
        });
    }

    private void setCreditAdapter() {
        dataBeanList = new ArrayList<>();
        creditAdapter = new CreditAdapter(getActivity());
        creditAdapter.setData(dataBeanList);
        mRecycleCredit.setLayoutManager(new LinearLayoutManager(getActivity()));
        mRecycleCredit.setAdapter(creditAdapter);
    }


    private class CreditAdapter extends RecyclerView.Adapter<CreditViewHolder> {
        private LayoutInflater inflater;
        private List<CreditListData.DataBean> list;

        private CreditAdapter(Context context) {
            inflater = LayoutInflater.from(context);
        }

        private void setData(List<CreditListData.DataBean> list) {
            this.list = list;
        }

        @Override
        public CreditViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            return new CreditViewHolder(inflater.inflate(R.layout.item_credit_dialog, parent, false));
        }

        @Override
        public void onBindViewHolder(final CreditViewHolder holder, final int position) {
            if (position + 1 <= list.size()) {
                CreditListData.DataBean dataBean = list.get(position);
                if (dataBean != null) {
                    String cardNum = list.get(position).getCard_code();
                    String lastNum = "(" + ("尾号" + cardNum.substring(cardNum.length() - 4, cardNum.length())) + ")";
                    holder.mText.setText(dataBean.getBank_name() + lastNum);
                    Glide.with(holder.itemView.getContext())
                            .load(CommonUtil.getPathFromAssets(dataBean.getBank_name(), getActivity()))
                            .into(holder.mImage);
                    holder.itemView.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            String phone = list.get(position).getMobile();
                            String card = list.get(position).getCard_code();
                            String cardId = String.valueOf(list.get(position).getId());
                            if (!CommonUtil.isEmpty(phone) && !CommonUtil.isEmpty(card) && !CommonUtil.isEmpty(cardId)) {
                                listener.onMobile(phone, card, cardId);
                            }
                            cancel();
                        }
                    });
                }
            } else {
                holder.itemView.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        listener.onMobile("", "", "");
                        cancel();
                    }
                });
            }
        }

        @Override
        public int getItemCount() {
            return list.size() + 1;
        }
    }

    public void setListener(Listener listener) {
        this.listener = listener;
    }

    private Listener listener;

    public static class Listener {
        public void onMobile(String phone, String card, String cardId) {

        }
    }

    private static class CreditViewHolder extends RecyclerView.ViewHolder {
        private ImageView mImage;
        private TextView mText;

        public CreditViewHolder(View itemView) {
            super(itemView);
            mImage = (ImageView) itemView.findViewById(R.id.item_credit_image);
            mText = (TextView) itemView.findViewById(R.id.item_credit_name);
        }
    }
}
